package com.atguigu.tingshu.payment.strategy.impl;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.client.OrderInfoFeignClient;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.strategy.PaymentStrategy;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.payment.WeChatPayVo;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class OrderPaymentStrategy implements PaymentStrategy {

    @Autowired
    private PaymentInfoService paymentInfoService ;

    @Autowired
    private RSAAutoCertificateConfig rsaAutoCertificateConfig ;

    @Autowired
    private WxPayV3Config wxPayV3Config ;

    @Autowired
    private OrderInfoFeignClient orderInfoFeignClient ;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient ;

    @Override
    public WeChatPayVo createJsapi(String paymentType, String orderNo) {

        // 根据订单的编号查询订单数据
        Result<OrderInfo> orderInfoResult = orderInfoFeignClient.getOrderInfo(orderNo);
        OrderInfo orderInfo = orderInfoResult.getData();
        if(SystemConstant.ORDER_STATUS_CANCEL.equals(orderInfo.getOrderStatus())) {     // 订单的状态为已取消
            return null ;
        }

        // 保存交易信息
        paymentInfoService.savePaymentInfo(orderInfo);

        WeChatPayVo weChatPayVo = this.requestWeChatPay(rsaAutoCertificateConfig, wxPayV3Config,
                orderInfo.getOrderTitle(), orderInfo.getOrderNo(), userInfoFeignClient);

        // 返回
        return weChatPayVo;
    }

    @Override
    public String getPaymentType() {
        return SystemConstant.PAYMENT_TYPE_ORDER;  // 1301
    }
}
